<template>
  <div class="app-container">
    <search-box :isMulti="false">
      <template slot="content">
        <div class="left-box">

          <el-form-item label="套餐名称：">
            <el-input v-model="listQuery.setMealName"
                      placeholder="请输入"
                      clearable/>
          </el-form-item>


        </div>
        <div class="right-box">
          <el-button size="mini" type="success"
                     @click="handleCreate">新增
          </el-button>

          <el-button size="mini"
                     @click="handleFilter">查询
          </el-button>
          <el-button size="mini" type="info"
                     @click="reset">重置
          </el-button>
        </div>
      </template>
    </search-box>
    <div class="table-wrap">
      <el-table :data="list"
                style="width:100%"
                element-loading-text="Loading"
                height="600"  width="150">
        <el-table-column
          type="index"
          width="50"
          label="序号"
        ></el-table-column>
<!--        会员卡号-->
        <el-table-column prop="setMealCode"
                         label="套餐编号" >
        </el-table-column>
        <el-table-column prop="setMealName"
                         label="套餐名称" >
        </el-table-column>
        <el-table-column prop="startTime"
                         label="套餐起止时间" >

          <template slot-scope="scope">
            <div >

              {{scope.row.startTime.substring(0,10)}}

            </div>
          </template>
        </el-table-column>
        <el-table-column prop="endTime"
                         label="套餐结束时间" >

          <template slot-scope="scope">
            <div >

              {{scope.row.endTime.substring(0,10)}}

            </div>
          </template>
        </el-table-column>
        <el-table-column prop="totalAmount"
                         label="套餐总金额" >
          <template slot-scope="scope">
            <div >
              ￥{{scope.row.totalAmount.toFixed(2)}}元
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="beforeFoldingPrice"
                         label="折前价格" >
          <template slot-scope="scope">
            <div >
              ￥{{scope.row.beforeFoldingPrice.toFixed(2)}}元
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="afterFoldingPrice"
                         label="折后价格" >
          <template slot-scope="scope">
            <div >
              ￥{{scope.row.afterFoldingPrice.toFixed(2)}}元
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="tableSetMealDetailList"
                         label="套餐详情" >
          <template slot-scope="scope">
            <div class="scope-operate">
              <el-button type="text" size="mini" @click="dialogTableVisible = true">套餐详情
              </el-button>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="操作"
                         width="200">
          <template slot-scope="scope">
            <div class="scope-operate">
              <el-button type="info" size="mini" @click="handleUpdate(scope.row)">编辑
              </el-button>
              <el-button type="danger" size="mini" @click="handleDelete(scope.row)">删除
              </el-button>

            </div>
          </template>
        </el-table-column>


      </el-table>
      <pagination v-show="total>0"
                  :total="total"
                  :page.sync="listQuery.pageNumber"
                  :limit.sync="listQuery.pageSize"
                  @pagination="getList"/>
    </div>


    <!--    //dialog弹窗 在页面的最后一个</div>的上面-->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      style="margin-top: -6%"
      width="30%"
      >
      <el-form ref="form" :model="form" :rules = 'rules' label-width="120px">
        <el-form-item label="套餐编号" prop="setMealCode">
          <el-input v-model="form.setMealCode"></el-input>
        </el-form-item>
        <el-form-item label="套餐名称" prop="setMealName">
          <el-input v-model="form.setMealName"></el-input>
        </el-form-item>
        <el-form-item label="套餐起止时间" prop="startTimeStr">
          <el-date-picker type="date" placeholder="选择日期" v-model="form.startTimeStr" style="width: 100%;" value-format="yyyy-MM-dd">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="套餐结束时间" prop="endTimeStr">
          <el-date-picker type="date" placeholder="选择日期" v-model="form.endTimeStr" style="width: 100%;" value-format="yyyy-MM-dd">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="套餐总金额" prop="totalAmount">
          <el-input v-model="form.totalAmount"></el-input>
        </el-form-item>
        <el-form-item label="折前价格" prop="beforeFoldingPrice">
          <el-input v-model="form.beforeFoldingPrice"></el-input>
        </el-form-item>
        <el-form-item label="折后价格" prop="afterFoldingPrice">
          <el-input v-model="form.afterFoldingPrice"></el-input>
        </el-form-item>
        <el-form-item label="套餐详情" prop="tableSetMealDetailListStr">
        <!-- 12+12=24 一个页面列的宽度之和不能超过24-->
            <el-col :span="18">
              <el-input v-model="form.tableSetMealDetailListStr"></el-input>
            </el-col>
            <el-col :span="6">
              <el-button type="info" size="mini" @click="handleChoose()">选择
              </el-button>
            </el-col>
          </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">提 交</el-button>
          <el-button @click="cancel">取消</el-button>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">

  </span>

    </el-dialog>





    <el-dialog
      title="选择套餐详情"
      :visible.sync="dialogVisibleChoose"
      width="30%"
    >

      <div>
        <el-form>
          <el-col :span="18">
            <el-form-item label="商品名称：">
              <el-input v-model="listQuery.proName"
                        placeholder="请输入"
                        clearable  style="width: 260px"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-button size="mini"
                       @click="handleFilterDialogTable">查询
            </el-button>
            <el-button size="mini" type="info"
                       @click="resetDialogTable">重置
            </el-button></el-col>
        </el-form>
      </div>

      <el-table :data="productList"
                style="width:100%"
                element-loading-text="Loading"
                width="300"
                @select="selectProInfo"
                @select-all="selectAllProInfo"
      >
        <el-table-column
          type="selection"
          name="type"
        ></el-table-column>
        <el-table-column prop="proCode"
                         label="商品编号" >
        </el-table-column>
        <el-table-column prop="proName"
                         label="商品名称" >
        </el-table-column>
        <el-table-column prop="proPrice"
                         label="商品价格" >
          <template slot-scope="scope">
            <div >
              ￥{{scope.row.proPrice.toFixed(2)}}元
            </div>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="totalDialogTable>0"
                  :total="totalDialogTable"
                  :page.sync="listQuery.pageNumber"
                  :limit.sync="listQuery.pageSize"
                  @pagination="getProductList"/>
      <span slot="footer" class="dialog-footer">
        <el-button @click="defineButton(type)">确 定</el-button>
        <el-button @click="dialogVisibleChoose = false">取 消</el-button>

    </span>
    </el-dialog>



    <!-- Table -->
<!--    <el-dialog title="套餐详情" :visible.sync="dialogTableVisible">-->
<!--      <el-table :data="tableSetMealDetailList">-->
<!--        <el-table-column property="date" label="日期" width="150"></el-table-column>-->
<!--        <el-table-column property="name" label="姓名" width="200"></el-table-column>-->
<!--        <el-table-column property="address" label="地址"></el-table-column>-->
<!--      </el-table>-->
<!--    </el-dialog>-->

    <!-- Form -->
<!--    <el-button type="text" @click="dialogFormVisible = true">打开嵌套表单的 Dialog</el-button>-->

<!--    <el-dialog title="收货地址" :visible.sync="dialogFormVisible">-->
<!--      <el-form :model="form">-->
<!--        <el-form-item label="活动名称" :label-width="formLabelWidth">-->
<!--          <el-input v-model="form.name" autocomplete="off"></el-input>-->
<!--        </el-form-item>-->
<!--        <el-form-item label="活动区域" :label-width="formLabelWidth">-->
<!--          <el-select v-model="form.region" placeholder="请选择活动区域">-->
<!--            <el-option label="区域一" value="shanghai"></el-option>-->
<!--            <el-option label="区域二" value="beijing"></el-option>-->
<!--          </el-select>-->
<!--        </el-form-item>-->
<!--      </el-form>-->
<!--      <div slot="footer" class="dialog-footer">-->
<!--        <el-button @click="dialogFormVisible = false">取 消</el-button>-->
<!--        <el-button type="primary" @click="dialogFormVisible = false">确 定</el-button>-->
<!--      </div>-->
<!--    </el-dialog>-->

  </div>
</template>

<script>
  import { mapGetters } from 'vuex'
  import { quillEditor } from 'vue-quill-editor'//添加富文本编辑器
  import 'quill/dist/quill.core.css'
  import 'quill/dist/quill.snow.css'
  import 'quill/dist/quill.bubble.css'

  import waves from '@/directive/waves' // waves directive
  import Pagination from '@/components/Pagination/index' // secondary package based on el-pagination
  // 当然你也可以为了方便使用，将它注册到全局
  import bus from '@/utils/eventBus'
  import searchBox from '@/components/searchBox.vue'
  import * as setMealDetail from '@/api/setMeal/setMealDetail'
  import * as setMeal from '@/api/setMeal/setMeal'
  import * as product from '@/api/product/product'
  export default {
    name: 'AdminUser',
    components: { Pagination, searchBox, quillEditor },
    directives: { waves },
    filters: {},
    data() {
      return {
        content: '',
        editorOption: {},
        list: null,
        setMealDetailList: null,
        areaList: null,
        productList: null,
        total: 0,
        totalDialogTable: 0,
        type: [],
        listQuery: { // 查询列表时的参数对象
          pageNumber: 1,
          pageSize: 50,
          appName: process.env.VUE_APP_APP_NAME,
          tenantIdList: []
        },
        selectionList: null,
        dialogVisible: false,
        dialogVisibleDesc: false,
        dialogVisibleChoose: false,
        dialogTitle:'',
        formLabelWidth: '120px',
        dialogTableVisible: false,
        dialogFormVisible: false,
        form:{
          startTimeStr: '',
          endTimeStr: '',
          totalAmount: '',
          beforeFoldingPrice: '',
          afterFoldingPrice: '',
          tableSetMealDetailList: ''
        },
        rules: {
          setMealCode: [{ required: true, message: '套餐编号必填', trigger: 'blur' }],
          setMealName: [{ required: true, message: '套餐名称必填', trigger: 'blur' }],
          startTimeStr: [{ required: true, message: '套餐起止时间必填', trigger: 'blur' }],
          endTimeStr: [{ required: true, message: '套餐结束时间必填', trigger: 'blur' }],
          tableSetMealDetailListStr: [{ required: true, message: '套餐明细必选', trigger: 'blur' }],
        }
      }
    },
    computed: {
      ...mapGetters([
        'selectedTenantId',
        'tenantList'
      ])
    },
    created() {

      this.$nextTick(() => {
        // this.$refs['form'].clearValidate()
      })
      this.getList()

      // 监听 租户改变的事件,选择不同租户后,立马刷新数据
      bus.$on('selectedTenantIdChanged', () => {
        console.log('selectedTenantIdChanged事件触发...')
        this.getList()
      })
    },
    mounted() {

    },
    beforeDestroy() { // 当路由切换到其他页面时触发
      bus.$off('selectedTenantIdChanged')
    },
    methods: { //所有的方法写在当前钩子函数下

      onEditorReady(editor) {
      },

      async getList() { // 获取列表数据
        this.listQuery.tenantIdList = []
        if (this.selectedTenantId == undefined) {//当前选中所有的租户
          this.tenantList.forEach((tenant, index) => {
            this.listQuery.tenantIdList.push(tenant.id)
          })
        } else {
          this.listQuery.tenantIdList.push(this.selectedTenantId)
        }
        const { content } = await setMeal.getSetMealList(this.listQuery)
        this.list = content.list
        this.total = content.totalCounts
      },

      async setMealDetail(row) { // 获取明细列表数据
        this.listQuery.tenantIdList = []
        this.listQuery.pageSize = 500;
        this.listQuery.setMealCode = row.setMealCode;
        if (this.selectedTenantId == undefined) {//当前选中所有的租户
          this.tenantList.forEach((tenant, index) => {
            this.listQuery.tenantIdList.push(tenant.id)
          })
        } else {
          this.listQuery.tenantIdList.push(this.selectedTenantId)
        }
        const { content } = await setMealDetail.getSetMealDetailList(this.listQuery)
        this.setMealDetailList = content.list
        this.listQuery.pageSize = 10;


        let tableSetMealDetail = '';
        for (let i = 0 ; i <this.setMealDetailList.length;i++ ){
          tableSetMealDetail+=(this.setMealDetailList[i].proName+',');
        }
        this.form.tableSetMealDetailListStr = tableSetMealDetail.substring(0,tableSetMealDetail.length-1);

      },

      async getProductList() { // 获取列表数据
        this.listQuery.tenantIdList = []
        if (this.selectedTenantId == undefined) {//当前选中所有的租户
          this.tenantList.forEach((tenant, index) => {
            this.listQuery.tenantIdList.push(tenant.id)
          })
        } else {
          this.listQuery.tenantIdList.push(this.selectedTenantId)
        }
        const { content } = await product.getProductList(this.listQuery)
        this.productList = content.list
        this.total = content.totalCounts
      },

      selectChanges(val) {
        this.selected = val;
      },
      handleFilter() {
        this.listQuery.pageNumber = 1
        this.getList()
      },
      handleChoose(){
        this.dialogVisibleChoose = true;
        this.setMealDetail();
        this.getProductList()
      },
      handleFilterDialogTable() {
        this.listQuery.pageNumber = 1
        this.getProductList()
      },
      selectDialogTableInfo(row, column){
        console.log('双击之后的数据',row);
        this.$set(this.form,'proCode',row.proCode)
        this.$set(this.form,'proName',row.proName)
        console.log('赋值之后的数据',this.form);
        this.dialogVisibleChoose = false
      },
      //新增数据
      handleCreate() {
        this.dialogVisible = true
        this.dialogTitle='新增'
      },
      //编辑数据
      handleUpdate(row) {

        this.dialogVisible = true
        this.dialogTitle='编辑';
        this.form = row;
        this.form.startTimeStr = row.startTime;
        this.form.endTimeStr = row.endTime;
        this.setMealDetail(row);

      },
      resetDialogTable() {
        this.listQuery = {}
        this.getProductList()
      },
      //删除数据
      handleDelete(row) {

        this.$confirm('是否删除?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          setMeal.deleteSetMeal(row).then(() => {
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '删除成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
          })
        }).catch(() => {
        })
      },


      handleLookProInfo(row){
        this.dialogVisibleDesc = true;
        this.proInfo = row;
      },


      handleRemove(file, fileList) {
        console.log(file, fileList);
      },
      handlePreview(file) {
        console.log(file);
      },

      //确定按钮
      defineButton(type){
        this.$set(this.form,'tableSetMealDetailList',type)
        this.dialogVisibleChoose = false
        let tableSetMealDetail = '';
        for (let i = 0 ; i <this.selectionList.length;i++ ){
          tableSetMealDetail+=(this.selectionList[i].proName+',');
        }
        this.form.tableSetMealDetailListStr = tableSetMealDetail.substring(0,tableSetMealDetail.length-1);
        this.form.tableSetMealDetailList = this.selectionList;
        console.log(this.form.tableSetMealDetailList);

      },

      selectProInfo(selection, row){
        console.log('selection',selection)
        console.log('row',row)
        this.selectionList = selection;
        console.log('this.selectionList',this.selectionList)
      },

      selectAllProInfo(selection){
        console.log('selection',selection)
        this.selectionList = selection;
        console.log('this.selectionList',this.selectionList)
      },


      //页面表单提交
      onSubmit(){
        this.$refs['form'].validate((valid) => {
          if (valid) {
            this.form.tenantId = this.$store.getters.selectedTenantId
            // this.form.proTime = this.form.proTimeStr;
            if (this.dialogTitle == '新增') {
              setMeal.createSetMeal(this.form).then((res) => {
                console.log(res)
                if (res.status == 200) {
                  this.$notify({
                    title: '成功',
                    message: '添加成功',
                    type: 'success',
                    duration: 2000
                  })
                  this.dialogVisible = false
                  this.getList()

                }
              })

            } else if (this.dialogTitle == '编辑') {

              setMeal.updateSetMeal(this.form).then((res) => {
                console.log(res)
                if (res.status == 200) {
                  this.$notify({
                    title: '成功',
                    message: '编辑成功',
                    type: 'success',
                    duration: 2000
                  })
                  this.dialogVisible = false
                  this.getList()

                }
              })


            }

          } else {
            console.log('error submit!!')
            return false
          }
        })


      },
      cancel(){
        this.dialogVisible = false;
        this.form = {};
      },
      reset() {
        this.listQuery = {}
        this.getList()
      }
    }
  }
</script>

<style scoped>
  .app-select {
    margin-bottom: 20px;
  }
</style>
